package com.hr.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hr.entity.R;
import com.hr.entity.Users;
import com.hr.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private UsersService usersService;

    /**
     * 认证（登录）成功，请求将转发到此方法
     * @return
     */
    @RequestMapping("/loginSuccess")
    public R loginSuccess(){
        Authentication authen = SecurityContextHolder.getContext().getAuthentication();
        Users user = (Users)authen.getPrincipal();

        return R.ok(user);
    }
    /**
     * 认证（登录）失败，请求将转发到此方法
     * @return
     */
    @RequestMapping("/loginFail")
    public R loginFail(){
        return R.fail("登录失败");
    }

    /**
     * 分页查询
     * @param page 分页参数
     * @return
     */
    @GetMapping("/queryList")
    public Page<Users> queryList(Page<Users> page){
        //调用service
        page = usersService.queryList(page);

        return page;
    }

    /**
     * 保存用户
     * @param user 如果前端传递了id，那么就是修改，否则就是添加
     * @return
     */
    @PostMapping("/save")
    public R save(
            //注意：axios post请求默认是json格式的数据
            // 需要 @RequestBody才能接收
            @RequestBody Users user){
        //对密码进行加密
        //我们security 这个框架配置的 BCrypt 加密算法类
        BCryptPasswordEncoder Encoder = new BCryptPasswordEncoder();
        String pwd = Encoder.encode(user.getUpassword());
        user.setUpassword(pwd);
        boolean b = usersService.save(user);
        return b ? R.ok("保存成功") : R.fail("保存失败");
    }

    /**
     * 删除接口
     * @param uid
     * @return
     */
    @DeleteMapping("/del")
    public R del(Integer uid){
        //调用service，根据id删除用户
        boolean b = usersService.delete(uid);

        return b ? R.ok("删除成功") : R.fail("删除失败");
    }

    /**
     * 单值查询接口
     * @param uid
     * @return
     */
    @GetMapping("/queryById")
    public Users queryById(Integer uid){
        Users users = usersService.queryById(uid);
        return users;
    }
}
